package com.jiajia.study.chapter01.nio;

import com.jiajia.study.utils.ByteBufferUtil;

import java.nio.ByteBuffer;

/**
 * 拆包和粘包 : 采用分隔符的方式 \n
 * @author zjiajia
 * @date 2024/7/5 10:31
 */
public class TestPackAndUnpack {
    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);

        byteBuffer.put("Hello,world\nI'm zhangsan\nHo".getBytes());
        split(byteBuffer);
        byteBuffer.put("w are you?\n".getBytes());
        split(byteBuffer);
    }

    /**
     * 这种方式的效率比较低，需要一个一个的
     * @param byteBuffer
     */
    public  static void split(ByteBuffer byteBuffer){
        // 切换成读模式
        byteBuffer.flip();
        for (int i = 0; i < byteBuffer.limit(); i++) {
            if('\n' == (byteBuffer.get(i))){
                int length = i+1 - byteBuffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(byteBuffer.get());
                }
                ByteBufferUtil.debugAll(target);
            }
        }
        byteBuffer.compact();
    }

}
